import Router from 'koa-router';
import { logger } from '../../../models/LogModel';
import { returnJson } from '../../../function';
import EthModel from '../../../models/eth/EthModel';
import { checkAddressChecksum, toChecksumAddress } from 'web3-utils';
import EthCoinType from '../../../database/eth/EthCoinType';
import net from 'net';
const router = new Router();

router.post('/getUserAddress/:uid', async (ctx, next) => {
  const ethModel = new EthModel;
  let uid = parseInt(ctx.params.uid); 
  // 参数检测
  if(isNaN(uid)) {
    // 抛异常
    logger('web').error(`uid 参数异常 ${ctx.params.uid}`);
    ctx.throw(403, returnJson(0, `参数异常`));
  }
  const address = await ethModel.createEthAddress(uid);
  ctx.body = returnJson(1, 'success', {address: address});
  await next();
})

router.post('/extract', async (ctx, next) => {
  let post = ctx.request.body;
  logger('web').info(`
    ${JSON.stringify(ctx.request.body)}
  `)

  let amount = parseInt(post.amount);
  if(isNaN(amount)){
    logger('web').error(`amount 参数异常 ${post.amount}`);
    ctx.throw(403, returnJson(0, `数量参数异常`));
  }

  let address = post.address;
  try {
    checkAddressChecksum(toChecksumAddress(address))  
  } catch (error) {
    logger('web').error(`address 校验失败 ${post.address}`);
    ctx.throw(403, returnJson(0, `地址校验失败 ${post.address}`));
  }

  let orderId = post.orderId;
  let contract_address = post.contract_address;

  try {
    const contractId = await EthCoinType.getCoinTypeId(contract_address);  
  } catch (error) {
    ctx.throw(403, returnJson(0, `不支持该币种提出合约地址 ${post.contract_address}`));
  }

  const extractObj = {
    address, 
    amount: post.amount, 
    contract_address, 
    orderId
  }
  
  try {
    net.connect(9090).write(JSON.stringify(extractObj));  
  } catch (error) {
    ctx.throw(403, returnJson(0, `提币服务异常`));
  }

  ctx.body = returnJson(1, 'success');
  return next();
});

export default router;